import { Square } from "./Square";
import { Points, Shape } from "./types";

// 方块组合类
export abstract class SquareGrounp {
  private _squares: ReadonlyArray<Square> = []

  public get squares() {
    return this._squares
  }

  /**
   * 方块组合类
   * @param _shape 形状
   * @param _centerPoint 中心点坐标
   * @param _color 颜色
   */
  constructor(
    private _shape: Shape,
    private _centerPoint: Points,
    private _color: string) {
    // 设置小方块是数组
    const arr: Square[] = []
    this._shape.forEach(p => {
      const sq = new Square()
      sq.color = this._color
      sq.point = sq.point = {
        x: p.x + this._centerPoint.x,
        y: p.y + this._centerPoint.y
      }
      arr.push(sq)
    })
    this._squares = arr
    // this.setSquarePoints()
  }

  get centerPoint(): Points {
    return this._centerPoint
  }
  // 中心移动
  set centerPoint(v: Points) {
    this._centerPoint = v
    // 同时数组其他小方块坐标
    this.setSquarePoints()
  }

  /**
   * 设置所有小方块的坐标
   */
  private setSquarePoints() {
    this._shape.forEach((p, i) => {
      this._squares[i].point = {
        x: p.x + this._centerPoint.x,
        y: p.y + this._centerPoint.y
      }
    })
  }

  get shape() {
    return this._shape
  }

  /**
   * 旋转方向是否为顺时针 true 顺时针 false 逆时针
   */
  private _isClock = true;

  get isClock() {
    return this._isClock
  }
  set isClock(val) {
    this._isClock = val
  }

  /**
   * 获取旋转之后的形状
   * @returns 形状
   */
  afterRotateShape(): Shape {
    return this._shape.map(({ x, y }) => {
      // 顺时针 x,y ==> -y,x
      // 逆时针 x,y ==> y,-x
      const newP: Points = this._isClock ? { x: -y, y: x } : { x: y, y: -x }
      return newP
    })
  }

  rotate() {
    // 获取新的形状
    const newShape = this.afterRotateShape()
    this._shape = newShape
    // 设置所有小方块的坐标
    this.setSquarePoints()
  }
}